var cur;
var time1,time2;
var sz=null;
var totalPic=4;
var best;

function startGame()
{
	// if (sz==null) init();
   if (cur!=null)
     {
         _gel("show_div").innerHTML="";
         delete cur;
     } 
   cur=new Game(); 
   time1=setTimeout("start2()",3000);
}

function start2()
{
  clearTimeout(time1);
  cur.messUp();
  cur.startTime=(new Date()).getTime(); 
  cur.state=1;
  time2=setTimeout("cur.refresh()",1000);
}

function gameOver()
{
	 var prefs = new _IG_Prefs(__MODULE_ID__);
	 
   if (cur==null || cur.state==3) return;
   clearTimeout(time1);
   clearTimeout(time2);
   cur.state=3;
   if (cur.win==true) 
     {
     	  cur.endTime=(new Date()).getTime();
     	  var score=timeInFormat(cur.endTime-cur.startTime);
     	  if (score.substr(0,1)=="T")  return;
     	  _gel("gameState_div").innerHTML="<p align='center' style='font-size: x-large;color: #6600FF'>Congratulations! Your Score:  "+score+"</p>";
     	 
     	  var i;
     	  
     	  best=prefs.getArray("TopScores_"+cur.width);
     	  
     	   for (i=0;i<5;i++)
     	     if (comp(best[i],score)>=0)
     	      {
     	     	   break;
     	      }
     	   for (var j=4;j>i;j--) best[j]=best[j-1];  
     	   if (i<5) best[i]=score;
     	   if (true)  prefs.setArray("TopScores_"+cur.width,best);
     	   cur.scores=best;
     	   time2=setTimeout("showScores("+i+")",2000);
     	   //_gel("show_div").innerHTML=showScores(best,i);
     	 
     };

}

function pause()
{
   if (cur)
   {
      if (cur.state==1)
       {
          cur.pauseStartTime=(new Date()).getTime();
          cur.state=2;
          _gel("pause").value="continue";
       }
       else
       if (cur.state==2)
       {
          cur.state=1;
          var temp=(new Date()).getTime();
          cur.startTime +=temp-cur.pauseStartTime;
          _gel("pause").value="pause";
       } 
   }
}



function Game()
{
   
   this.imageSettings();
   
   this.state=0;
   this.startTime=this.endTime=null;
   this.pauseStartTime=null;
   this.click1=-1;
   this.win=false;
   
   this.loadPicture();

   _gel("show_div").appendChild(this.table);
   
}

Game.prototype.imageSettings=function()
{
	  var size,imgnum;
	   
	  if (true)
	  {
	  var prefs = new _IG_Prefs(__MODULE_ID__);
	  size=parseInt(prefs.getString("difficulty"));
	  imgnum=prefs.getString("picture");
	  imgnum=parseInt(imgnum.substr(3,imgnum.length-3));
	  }
	  else
	  {
	  	 size=3;
	  	 imgnum=0;
	  	
	  }
	  
	  if (size>=3 && size<=7)
	   {
	   	  this.width=this.height=size;
	   }
	   else this.width=this.height=3;
	  
	  if (imgnum>=0 && imgnum<totalPic)
	   {
	   	 this.imagesource=sz[imgnum];
	   }
	    else this.imagesource=sz[0];
	   
	  /*
	  var pic=this.getImageObject(0,0);
	  var width,height;
	  var rate;
	  
	  width=pic.style.width;
	  height=pic.style.height;
	  rate=1.0*300/pic.width;
	  width=300;
	  height=Math.floor(rate*height);  */
	  
	  this.picwidth=300; 
	  this.picheight=300;
	  if (this.picheight<200) this.picheight=300; 
	  //var rate=300.0/this.picwidth;
	  //this.picwidth=300;
	  //this.picheight=Math.floor(rate*this.picheight);
	  
	  this.cellwidth=Math.floor(this.picwidth*1.0/this.width);
    this.cellheight=Math.floor(this.picheight*1.0/this.height);
    
}
                                                 
Game.prototype.getImageObject=function(sh,sw)
{
   var temp;
   temp=document.createElement("img");
   temp.src=this.imagesource;
   if (sh>0 || sw>0) temp.style.margin=" "+(-sh)+"px 0px 0px "+(-sw)+"px";        // top right bottom left
   return temp;
}

Game.prototype.loadPicture=function()
{
    var i,j;
    this.table=document.createElement("table");
    this.cell_content=new Array(this.width*this.height);
    this.answer=new Array(this.width*this.height);
    
    for (i=0;i<this.height;i++)
     {
       var line=document.createElement("tr");
         for (j=0;j<this.width;j++)
          {
             var cell=document.createElement("td"); 
             cell.id="t_"+(i*this.width+j);  
             cell.onclick=this.handleClick(i,j);
             //cell.class="TableCells";
             var div_cell=document.createElement("div");
             div_cell.style.overflow="hidden";
             div_cell.style.width=this.cellwidth;
             div_cell.style.height=this.cellheight;
             
             div_cell.id="c_"+(i*this.width+j);
             
             //div_cell.class="DivCells";
             var imgtemp=this.getImageObject(i*this.cellheight,j*this.cellwidth);
             imgtemp.width=this.picwidth; 
             imgtemp.height=this.picheight;
             div_cell.appendChild(imgtemp);
             this.cell_content[i*this.width+j]=div_cell;         
             this.answer[i*this.width+j]=div_cell;    
             cell.appendChild(div_cell);
             line.appendChild(cell);
          }
       this.table.appendChild(line);   
     }     
 //  _gel("show_div").appendChild(this.table);
}

Game.prototype.messUp=function()
{
   var messDegree;
   var total=this.height*this.width;
   
   switch (this.width)
   {
     case 3: messDegree=7; break;
     case 4: messDegree=10; break;
     case 5: messDegree=12; break;
     case 6: messDegree=15; break;
     case 7: messDegree=20; break;
   } 
   for (var i=0;i<messDegree;i++)
    {  
       var x,y;
       x=Math.floor(Math.random()*total);
       do 
       {
          y=Math.floor(Math.random()*total);
       }
       while (x==y);
      
       var x2,y2,temp;
       x2=_gel("t_"+x); 
       y2=_gel("t_"+y);
       x2.appendChild(y2.firstChild);
       y2.appendChild(x2.firstChild);
       temp=this.cell_content[x];
       this.cell_content[x]=this.cell_content[y];
       this.cell_content[y]=temp;
    }
}

Game.prototype.refresh=function()
{
   if (cur.state==1 && cur.win==false)
   {
     var timeInfo;
     timeInfo=timeInFormat((new Date()).getTime()-this.startTime);
     if (timeInfo=="Time Expired") 
     {
        clearTimeout(time2);
        timeInfo="<p align='center'>"+timeInfo+"</p>";
        _gel("gameState_div").innerHTML=timeInfo;
        cur.gameOver();
        return;
     };
    timeInfo="<p align='center' style='font-size: x-large; color: #6600FF;'>"+timeInfo+"</p>";
    _gel("gameState_div").innerHTML=timeInfo;
   }
   clearTimeout(time2);
   time2=setTimeout("cur.refresh()",1000);
}

Game.prototype.handleClick = function(x,y)
{
    var self=this;
    return function()
    {
       self.handleClick2(x,y);
    } 
}

Game.prototype.handleClick2 =function(x,y)
{
	 if (this.state!=1) return;
	 
   if (this.click1==-1)
   {
      this.click1=x*this.width+y;
      var now=this.cell_content[this.click1];
      now.style.border="solid 2px lime";  
   }
   else 
   { 
      var click2=x*this.width+y;
      var before=this.cell_content[this.click1];
      var now=this.cell_content[click2];
      before.style.border="solid 0px lime";
      now.style.border="solid 0px lime";
      if (click2!=this.click1)
       {
          var temp1,temp2;
          
          temp1=this.cell_content[this.click1];
          this.cell_content[this.click1]=this.cell_content[click2];
          this.cell_content[click2]=temp1;
          
          temp1=before.parentNode; temp2=now.parentNode;
          temp1.appendChild(now);
          temp2.appendChild(before);
       }
     this.click1=-1;  
   }
   
   this.checkWin();
}

Game.prototype.checkWin=function()
{
   var i,j;
   
   for (i=0;i<this.height;i++)
    for (j=0;j<this.width;j++)
     {
        var num=i*this.width+j;
        if (this.cell_content[num].id!=("c_"+num)) 
         {
            this.win=false;
            return;
         };
     }
   
   this.win=true;
   gameOver();  
}

 function timeInFormat(t)
  {
         var sec=parseInt(t/1000);
         var min=parseInt(sec/60);
         if (min>59) return "Time Expired";
         var sec=sec % 60;
         if (min<10) min="0"+min;
         if (sec<10) sec="0"+sec;
         return min+":"+sec;  
  }
  
 function init()
 {
    var dir="http://jigsawgame2.googlecode.com/svn/trunk/resources/";
    
 	  sz=new Array(totalPic);
 	  sz[0]=dir+"MINNIE.jpg";
 	  sz[1]=dir+"weenie.jpg";
 	  sz[2]=dir+"Snoopy.jpg";
 	  sz[3]=dir+"desert.jpg";
 	  
 	  /*best=new Array(5);
     	   	  best[0]="00:30";
     	   	  best[1]="02:00";
     	   	  best[2]="05:00";
     	   	  best[3]="10:00";
     	   	  best[4]="20:00"; */
 	
 }
  
 function comp(a, b) 
 {
   if (a.substr(0, 2) > b.substr(0, 2)) {
    return 1;
   } 
   else 
   	if (a.substr(0, 2) == b.substr(0, 2)) 
   	{
       if (a.substr(3, 2) > b.substr(3, 2)) 
        {
          return 1;
        }
       else
       if (a.substr(3, 2)==b.substr(3, 2)) return 0; 
    }
   return -1;
}

function showScores(i)
 {
 	  clearTimeout(time2);
 	  var output="<div style='border: solid 3px #333333; background-image: url(http://jigsawgame2.googlecode.com/svn/trunk/resources/bg2.jpg); margin: 5px; height: auto' align='center'>";
    output  += "<div align='center'><span class='STYLE1'>Best Scores for ";
    output  +=cur.width+"*"+cur.height+"</span> </div>";
    output +="<table width='300' height='260' border='2' background='http://jigsawgame2.googlecode.com/svn/trunk/resources/bg3.jpg' align='center'>";
    output +="<tr> <th width='101' scope='col'><span class='STYLE3'>rank</span></th> <th scope='col'><span class='STYLE3'>score</span></th></tr>";
    for (var loop=0;loop<5;loop++)
    {
       output +="<tr><th scope='row'>"+(loop+1)+"</th><td><div align='center' class=";
       if (i==loop) output +="'STYLE2BOLD'"; else output +="'STYLE2'";
       output +=">"+best[loop]+"</div></td></tr>";
    }
    output +="</table></div>";            
 	  _gel("show_div").innerHTML=output;
 }
 
 _IG_RegisterOnloadHandler(init());